package xzit.gcxy.xxhzx.zhh.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import xzit.gcxy.xxhzx.zhh.common.AjaxJson;
import xzit.gcxy.xxhzx.zhh.entity.InstituteVO;
import xzit.gcxy.xxhzx.zhh.service.SystemService;

@Controller
@RequestMapping("/instituteController")
public class InstituteController {
	private static final Logger logger = Logger.getLogger(InstituteController.class);

	@Autowired
	private SystemService systemService;

	/**
	 * 科研工作量详情页
	 * 
	 * @param error
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goInstitute")
	public ModelAndView goSWDetail(HttpServletRequest request) {
		return new ModelAndView("system/institute");
	}

	/**
	 * 初始访问
	 * 
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goAccount")
	public ModelAndView goScore(HttpServletRequest request) {
		return new ModelAndView("system/account");
	}

	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(HttpServletRequest request, HttpServletResponse response, InstituteVO vo)
			throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("保存成功！");
		j.setSuccess(true);
		try {
			systemService.save(vo);
		} catch (Exception e) {
			j.setMsg("保存失败！");
			j.setSuccess(false);
		}
		return j;

	}


	@RequestMapping(params = "datagrid")
	@ResponseBody
	public void datagrid(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String page = request.getParameter("page");// easyui datagrid 分页 页号
		String rows = request.getParameter("rows");// easyui datagrid 分页 页数
		if (page == null) {
			page = "0";
		}
		if (rows == null) {
			rows = "0";
		}
		DetachedCriteria condition = DetachedCriteria.forClass(InstituteVO.class);
		List<InstituteVO> voList = systemService.getQueryData(condition);

		List<InstituteVO> dataret = new ArrayList<InstituteVO>();
		int start = (Integer.parseInt(page) - 1) * Integer.parseInt(rows);
		while(dataret.size()<Integer.parseInt(rows) && start < voList.size()){
			dataret.add(voList.get(start++));
		}
		
		JSONObject jobj = new JSONObject();
		jobj.put("total", voList.size());
		jobj.put("rows", dataret);

		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());

	}
}
